<?php

namespace Gds\VenteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Gds\VenteBundle\Entity\BonCommandeClient;
use Gds\VenteBundle\Form\BonCommandeClientType;
use Gds\VenteBundle\Entity\LigneBonCommandeClient;
use Gds\ArticleBundle\Entity\Societe;
use Symfony\Component\HttpFoundation\Response;
use Gds\VenteBundle\Entity\BonLivraisonClient;
use Gds\VenteBundle\Form\BonLivraisonClientType;
use Gds\VenteBundle\Entity\LigneBonLivraisonClient;

class BonCommandeController extends Controller {

    public function indexAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $ref = $societe->getPrefixeBonCommandeClient();
        $ref_num = $societe->getNumeroBonCommandeClient();
        $bon_commande = new BonCommandeClient();
        $bon_commande->setReference($ref . ' ' . $ref_num);
        $request = $this->getRequest();
        $form = $this->createForm(new BonCommandeClientType, $bon_commande);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            try {
                $articles = json_decode($request->get('articles'));
                $heure = $request->get('heure');
                $nom_dep = $request->get('departement');
                $departement = $em->getRepository('GdsArticleBundle:Departement')->findOneByNom($nom_dep);
                $form->bind($request);
                $bon_commande = $form->getData();
                $bon_commande->setHeure($heure);
                foreach ($articles->articles as $article) {
                    $ligne = new LigneBonCommandeClient();
                    $art = $em->getRepository('GdsArticleBundle:Article')->find($article->id);
                    $ligne->setArticle($art);
                    $ligne->setQuantite($article->quantite);
                    $bon_commande->addLignesBonCommande($ligne);
                }
                $ref_num = $societe->getNumeroBonCommandeClient();
                $societe->setNumeroBonCommandeClient($ref_num + 1);
                $bon_commande->setReference($ref . ' ' . $ref_num);
                $bon_commande->setUser($user);
                $bon_commande->setDepartement($departement);
                $em->persist($bon_commande);
                $em->persist($societe);
                $em->flush();
                $response = new Response(json_encode(array('success' => true)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        return $this->render('GdsVenteBundle:BonCommande:bon_commande.html.twig', array('form' => $form->createView(), 'user' => $user));
    }

    public function getAllArticlesBonCommandeAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $articles = $em->getRepository('GdsArticleBundle:Article')->findAll();
        $result = array();
        $k = 0;
        foreach ($articles as $article) {
            if ($article->getIsSupprimer() == false) {
                $result[$k]['designation'] = $article->getDesignation();
                $result[$k]['reference'] = $article->getReference();
                $result[$k]['quantite'] = 1;
                $name = $article->getReference() . ' : ' . $article->getDesignation();
                $result[$k]['name'] = $name;
                $result[$k]['id'] = $article->getId();
                $k++;
            }
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getArticlesBonCommandeWhereFamillesAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $familles = json_decode($request->get('familles'));
        $sous_familles = $familles->sous_familles;
        if (count($sous_familles) == 0) {
            $familles = $familles->familles;
            $all_familles = $familles;
            foreach ($familles as $famille) {
                $sous_familles = $em->getRepository('GdsArticleBundle:Famille')->findBy(array('famille_mere' => $famille, 'is_supprimer' => 0));
                foreach ($sous_familles as $sous_famille)
                    array_push($all_familles, $sous_famille->getId());
            }
            $familles = $all_familles;
        }
        else
            $familles = $familles->sous_familles;
        $result = array();
        $k = 0;
        foreach ($familles as $id_famille) {
            $articles = $em->getRepository('GdsArticleBundle:Article')->findByFamille($id_famille);
            foreach ($articles as $article) {
                if ($article->getIsSupprimer() == false) {
                    $result[$k]['designation'] = $article->getDesignation();
                    $result[$k]['reference'] = $article->getReference();
                    $result[$k]['quantite'] = 1;
                    $name = $article->getReference() . ' : ' . $article->getDesignation();
                    $result[$k]['name'] = $name;
                    $result[$k]['id'] = $article->getId();
                    $k++;
                }
            }
        }
        if (count($familles) == 0) {
            $articles = $em->getRepository('GdsArticleBundle:Article')->findAll();
            foreach ($articles as $article) {
                if ($article->getIsSupprimer() == false) {
                    $result[$k]['designation'] = $article->getDesignation();
                    $result[$k]['reference'] = $article->getReference();
                    $result[$k]['quantite'] = 1;
                    $name = $article->getReference() . ' : ' . $article->getDesignation();
                    $result[$k]['name'] = $name;
                    $result[$k]['id'] = $article->getId();
                    $k++;
                }
            }
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getAllBonCommandesAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $num = $request->get('numero');
        $raison = $request->get('raison_social');
        $date1 = $request->get('date1');
        $date2 = $request->get('date2');
        $heure1 = $request->get('heure1');
        $heure2 = $request->get('heure2');
        $ref = $request->get('reference');
        $des = $request->get('designation');
        $is_cloturer = $request->get('is_cloture');
        $departement = $request->get('departement');
        $user = $this->getUser();
        if (!$request->get('type') && !$request->get('retour'))
            $departement = $user->getDepartement()->getId();
        if ($is_cloturer == 2)
            $is_cloturer = '';

        $query = $em->getRepository('GdsVenteBundle:BonCommandeClient')->getResult($num, $raison, $date1, $date2, $heure1, $heure2, $ref, $des, $is_cloturer, $departement);
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $query, $request->get('page', 1)/* page number */, 10/* limit per page */
        );

        if ($request->get('type')) {
            return $this->render('GdsVenteBundle:BonCommande:page_liste_bon_commande.html.twig', array('pagination' => $pagination, 'departement' => $departement));
        }
        if ($request->get('retour') != "")
            return $this->render('GdsVenteBundle:BonCommande:liste_bon_commande.html.twig', array('pagination' => $pagination, 'departement' => $departement));
        return $this->render('GdsVenteBundle:BonCommande:all_bon_commande.html.twig', array('pagination' => $pagination, 'departement' => $user->getDepartement()->getId()));
    }

    public function showAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $bon_commande = $em->getRepository('GdsVenteBundle:BonCommandeClient')->find($id);
        $lignes = $em->getRepository('GdsVenteBundle:LigneBonCommandeClient')->findBy(array('bon_commande' => $bon_commande));
        return $this->render('GdsVenteBundle:BonCommande:bon_commande_show.html.twig', array('bon_commande' => $bon_commande, 'lignes' => $lignes));
    }

    public function editAction() {
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getEntityManager();
        $bon_commande = $em->getRepository('GdsVenteBundle:BonCommandeClient')->find($id);
        $form = $this->createForm(new BonCommandeClientType, $bon_commande);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            foreach ($bon_commande->getLignesBonCommande() as $ligne) {
                $em->remove($ligne);
            }
            $em->flush();
            try {
                $articles = json_decode($request->get('articles'));
                $heure = $request->get('heure');
                $form->bind($request);
                $bon_commande = $form->getData();
                $bon_commande->setHeure($heure);
                $bon_commande->setUser($user);
                foreach ($articles->articles as $article) {
                    $ligne = new LigneBonCommandeClient();
                    $art = $em->getRepository('GdsArticleBundle:Article')->find($article->id);
                    $ligne->setArticle($art);
                    $ligne->setQuantite($article->quantite);
                    $bon_commande->addLignesBonCommande($ligne);
                }
                $em->persist($bon_commande);
                $em->flush();
                $response = new Response(json_encode(array('success' => true)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        $time = $bon_commande->getTime();
        $heure = $bon_commande->getHeure();
        $lignes = array();
        foreach ($bon_commande->getLignesBonCommande() as $k => $ligne) {
            $lignes[$k] = $ligne;
        }
        return $this->render('GdsVenteBundle:BonCommande:bon_commande_edit.html.twig', array('form' => $form->createView(), 'heure' => $heure, 'time' => $time, 'lignes' => $lignes, 'id' => $id, 'user' => $user));
    }

    public function duppliquerAction() {
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getEntityManager();
        $old_bon_commande = $em->getRepository('GdsVenteBundle:BonCommandeClient')->find($id);
        $bon_commande = clone $old_bon_commande;
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $pref = $societe->getPrefixeBonCommandeClient();
        $num = $societe->getNumeroBonCommandeClient();
        $bon_commande->setReference($pref . ' ' . $num);
        $form = $this->createForm(new BonCommandeClientType, $bon_commande);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            try {
                $articles = json_decode($request->get('articles'));
                $heure = $request->get('heure');
                $nom_dep = $request->get('departement');
                $departement = $em->getRepository('GdsArticleBundle:Departement')->findOneByNom($nom_dep);
                $form->bind($request);
                $bon_commande = $form->getData();
                $bon_commande->setHeure($heure);
                foreach ($articles->articles as $article) {
                    $ligne = new LigneBonCommandeClient();
                    $art = $em->getRepository('GdsArticleBundle:Article')->find($article->id);
                    $ligne->setArticle($art);
                    $ligne->setQuantite($article->quantite);
                    $bon_commande->addLignesBonCommande($ligne);
                }
                $ref_num = $societe->getNumeroBonCommandeClient();
                $societe->setNumeroBonCommandeClient($ref_num + 1);
                $bon_commande->setReference($pref . ' ' . $ref_num);
                $bon_commande->setUser($user);
                $bon_commande->setDepartement($departement);
                $em->persist($societe);
                $em->persist($bon_commande);
                $em->flush();
                $response = new Response(json_encode(array('success' => true)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        $time = $bon_commande->getTime();
        $heure = $bon_commande->getHeure();
        $lignes = array();
        foreach ($bon_commande->getLignesBonCommande() as $k => $ligne) {
            $lignes[$k] = $ligne;
        }
        return $this->render('GdsVenteBundle:BonCommande:bon_commande_duppliquer.html.twig', array('form' => $form->createView(), 'heure' => $heure, 'time' => $time, 'lignes' => $lignes, 'id' => $id, 'user' => $user));
    }

    public function deleteAction() {
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getEntityManager();
        $bon_commande = $em->getRepository('GdsVenteBundle:BonCommandeClient')->find($id);
        $bon_commande->setIsSupprimer(true);
        $em->persist($bon_commande);
        $em->flush();
        return new Response('success');
    }

    public function livrerAction() {
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getEntityManager();
        $bon_commande = $em->getRepository('GdsVenteBundle:BonCommandeClient')->find($id);
        $bon_livraison = new BonLivraisonClient();
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $pref = $societe->getPrefixeBonLivraison();
        $num = $societe->getNumeroBonLivraison();
        $bon_livraison->setReference($pref . ' ' . $num);
        $form = $this->createForm(new BonLivraisonClientType, $bon_livraison);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            try {
                $articles = json_decode($request->get('articles'));
                if (count($articles->articles) == 0) {
                    $response = new Response(json_encode(array('success' => false)));
                    $response->headers->set('Content-Type', 'application/json');
                    return $response;
                }
                $heure = $request->get('heure');
                $form->bind($request);
                $bon_livraison = $form->getData();
                $client = $bon_livraison->getClient();
                $is_facturable = $request->get('facturable');
                $nom_dep = $request->get('departement');
                $departement = $em->getRepository('GdsArticleBundle:Departement')->findOneByNom($nom_dep);
                $bon_livraison->setHeure($heure);
                $montant_bl_ttc = 0;
                $montant_noir_ttc = 0;
                foreach ($articles->articles as $json_article) {
                    $article = $em->getRepository('GdsArticleBundle:Article')->find($json_article->id);
                    $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));
                    if ($is_facturable == 'true')
                        $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock, 'is_noir' => 0), array('prix_achat_ttc' => 'ASC'));
                    else
                        $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock), array('is_noir' => 'DESC', 'prix_achat_ttc' => 'ASC'));
                    $quantite = $json_article->quantite;
                    $quantite_blanc = 0;
                    $quantite_noir = 0;
                    $prix_achat_ttc = 0;
                    $i = 0;
                    while ($quantite > 0 && $i < count($stock_achat)) {
                        if ($quantite <= $stock_achat[$i]->getQuantite()) {
                            $stock_achat[$i]->setQuantite($stock_achat[$i]->getQuantite() - $quantite);
                            $prix_achat_ttc += $stock_achat[$i]->getPrixAchatTtc() * $quantite;
                            if ($stock_achat[$i]->getIsNoir())
                                $quantite_noir += $quantite;
                            else
                                $quantite_blanc += $quantite;
                            $quantite = 0;
                        } else {
                            $prix_achat_ttc += $stock_achat[$i]->getPrixAchatTtc() * $stock_achat[$i]->getQuantite();
                            if ($stock_achat[$i]->getIsNoir())
                                $quantite_noir += $stock_achat[$i]->getQuantite();
                            else
                                $quantite_blanc += $stock_achat[$i]->getQuantite();
                            $quantite -= $stock_achat[$i]->getQuantite();
                            $stock_achat[$i]->setQuantite(0);
                            $em->remove($stock_achat[$i]);
                        }
                        $i++;
                    }
                    if ($quantite > 0) {
                        $prix_achat_ttc += $article->getPrixAchatHt() * (1 + $article->getTauxTva() / 100) * $quantite;
                        if ($is_facturable == 'true')
                            $quantite_blanc += $quantite;
                        else
                            $quantite_noir += $quantite;
                    }
                    $stock->setQuantiteBlanc($stock->getQuantiteBlanc() - $quantite_blanc);
                    $stock->setQuantiteNoir($stock->getQuantiteNoir() - $quantite_noir);
                    $prix_achat_ttc /= $json_article->quantite;
                    $montant_bl_ttc += $json_article->prix_vente * $quantite_blanc;
                    $montant_noir_ttc += $json_article->prix_vente * $quantite_noir;
                    $ligne = new LigneBonLivraisonClient();
                    $ligne->setArticle($article);
                    $ligne->setQuantiteBlanc($quantite_blanc);
                    $ligne->setQuantiteNoir($quantite_noir);
                    $ligne->setQuantiteRetour(0);
                    $ligne->setPrixUnitaireHt($json_article->prix_vente);
                    $ligne->setPrixAchatTtc($prix_achat_ttc);
                    $ligne->setTauxRemise($json_article->remise);
                    $ligne->setTauxTva($json_article->taux_tva);
                    $bon_livraison->addLignesBonLivraison($ligne);
                    $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $article));
                    if ($categorie_remise != null)
                        $categorie_remise->setRemise($json_article->remise);
                    else {
                        $categorie_remise = new CategorieRemise();
                        $categorie_remise->setArticle($article);
                        $categorie_remise->setClient($client);
                        $categorie_remise->setRemise($json_article->remise);
                        $em->persist($categorie_remise);
                    }
                }
                $ref_num = $societe->getNumeroBonLivraison();
                $societe->setNumeroBonLivraison($ref_num + 1);
                $bon_livraison->setReference($pref . ' ' . $ref_num);
                $bon_livraison->setReste($montant_bl_ttc + $montant_noir_ttc);
                $bon_livraison->setMontantBlancTtc($montant_bl_ttc);
                $bon_livraison->setMontantNoirTtc($montant_noir_ttc);
                $bon_livraison->setBonCommande($bon_commande);
                $bon_livraison->setUser($user);
                $devis = $bon_commande->getDevis();
                if ($devis) {
                    $bon_livraison->setDevis($devis);
                    $devis->setIsCloturer(true);
                }
                $bon_commande->setIsCloturer(true);
                $bon_livraison->setDepartement($departement);
                $em->persist($bon_livraison);
                $em->flush();
                $response = new Response(json_encode(array('success' => true)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        $lignes_devis = array();
        $lignes_bon_commande = array();
        $devis = $bon_commande->getDevis();
        if ($devis != null) {
            foreach ($devis->getLignesDevis() as $k => $ligne) {
                $lignes_devis[$k] = $ligne;
            }
        } else {
            $client = $bon_commande->getClient();
            foreach ($bon_commande->getLignesBonCommande() as $k => $ligne) {
                $ligne_bon = array();
                $article = $ligne->getArticle();
                $ligne_bon['reference'] = $article->getReference();
                $ligne_bon['designation'] = $article->getDesignation();
                $ligne_bon['quantite'] = $ligne->getQuantite();
                $ligne_bon['prixVente'] = $article->getPrixVente();
                $ligne_bon['tauxTva'] = $article->getTauxTva();
                $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('article' => $article, 'client' => $client));
                $ligne_bon['tauxRemise'] = $categorie_remise->getRemise();
                $ligne_bon['remiseMax'] = $article->getRemiseMax();
                $ligne_bon['id'] = $article->getId();
                $lignes_bon_commande[$k] = $ligne_bon;
            }
        }
        return $this->render('GdsVenteBundle:BonCommande:bon_commande_to_bon_livraison.html.twig', array('form' => $form->createView(), 'lignesdevis' => $lignes_devis, 'lignesbon' => $lignes_bon_commande, 'id' => $id, 'user' => $user));
    }

}
